#include <libdswserver/dswservercenter.h>

#define TIMEOUT_CREATESERVER 5
#define defVideoBase 10000
#define defMsgBase 14000

CDswservercenter::CDswservercenter(LPST_ENV_T pEnv)
: CDswbase(pEnv)
, m_pAVServer(NULL)
, m_pMsgServer(NULL)
{
	LOG4CPLUS_DEBUG(log_dsw, "Create CDswservercenter class!");
	CREATE_EV(m_nCreateSvrTask, TIMEOUT_CREATESERVER, 0, pEnv->pEvBase, CDswservercenter::cbCreateLocalServersTask, this);
}

CDswservercenter::~CDswservercenter()
{
	CLEAR_EV(m_nCreateSvrTask);
	if (m_pAVServer)
		delete m_pAVServer;
	if (m_pMsgServer)
		delete m_pMsgServer;
	LOG4CPLUS_DEBUG(log_dsw, "Destroy CDswservercenter class!");
}

void CDswservercenter::CreateLocalServersTask(int fd, short events)
{
	unsigned long nIp;
	SendMessage(PMSG_GET_ACTIVE_IP, (void*)&nIp);
	if (nIp != 0){
		m_pAVServer = new CDswavserver(m_pEnv, defVideoBase + (((nIp >> 24) & 0x000000ff) * 4));
		m_pMsgServer = new CDswmsgserver(m_pEnv, defMsgBase + (((nIp >> 24) & 0x000000ff) * 4));
	}
	else
		TRIG_EV(m_nCreateSvrTask, TIMEOUT_CREATESERVER, 0);
}

int CDswservercenter::OnMessage(EN_MSG_TYPE nMsgType, void * pParam)
{
	switch(nMsgType){
	case PMSG_GET_VIDEOLISTEN_PORT:
		if (m_pAVServer)
			*((int*)pParam) = m_pAVServer->GetServerPort();
		else
			*((int*)pParam) = 0;
		break;
	case PMSG_GET_MSGLISTEN_PORT:
		if (m_pMsgServer)
			*((int*)pParam) = m_pMsgServer->GetServerPort();
		else
			*((int*)pParam) = 0;
		break;
	case PMSG_SET_UPDATE_FWDSESSION:
	case PMSG_SET_AVSESSION_ADD:
	case PMSG_SET_AVSESSION_REMOVE:
	case PMSG_SET_REC_VIDEO_OP:
	case PMSG_GET_ISLIVEVIDEO:
	case PMSG_GET_TOTALREC_UPDATE:
	case PMSG_SET_UPDATE_TIMEZ:
		if (m_pAVServer)
			m_pAVServer->HandleMessage(nMsgType, pParam);
		break;
	}
	return 0;
}

